/*
 * @Author: 张仁会 28396543@qq.com
 * @Date: 2022-03-24 09:33:24
 * @LastEditors: 张仁会 28396543@qq.com
 * @LastEditTime: 2022-09-08 11:38:04
 * @FilePath: \react-app\src\pages\login\index.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom';
import axios from 'axios'

class Login extends Component {
  state = {
    isLogin: true,
    username: '',
    password: '',
    userList: [{ user: 'qwe', password: '123' }]
  }
  static getDerivedStateFromProps(props, state) {
    if (state.username && state.password) {
      return { isLogin: false }
    }
    return { isLogin: true }
  }
  componentDidMount() {
    // axios.get('/userList.json').then(({ data }) => {
    //   this.setState({ userList: data })
    // })
  }
  render() {
    let { isLogin, username, password, userList } = this.state;
    return (
      <div className='login'>
        <div className='con'>
          <p>账号: <input type="text" placeholder='qwe' onChange={(e) => { this.setState({ username: e.target.value }) }} /></p>
          <p>密码: <input type="text" placeholder='123' onChange={(e) => { this.setState({ password: e.target.value }) }} /></p>
          <p><button onClick={this.login} disabled={isLogin}>登录</button></p>
        </div>
      </div>
    )
  }
  login = () => {
    let { username, password, userList } = this.state;
    // 筛选账号是否存在
    let resault = userList.filter(item => {
      if (item.user === username) {
        return item
      }
    })
    if (resault.length <= 0) {
      alert('账号不存在')
    } else {
      // 判断密码是否正确
      if (password === resault[0].password) {
        localStorage.setItem('token', username)
        this.props.history.push('/layout')
        console.log(this.props.history);
      } else {
        alert('密码不正确')
      }
    }
  }
}

export default withRouter(Login)

